package j20251128;

import java.util.*;

public class Solution {
    public List<String> topKFrequent(String[] words, int k) {
        HashMap<String,Integer> set=new HashMap<>();
        for(String str:words){
            if(set.get(str)==null){
                set.put(str,1);
            }else{
                int val=set.get(str);
                set.put(str,val+1);
            }
        }
        PriorityQueue<Map.Entry<String,Integer>> minHeap=new PriorityQueue<>((a, b)->{
            if(a.getValue().compareTo(b.getValue())==0){
                return b.getKey().compareTo(a.getKey());
            }
            return a.getValue().compareTo(b.getValue());
        });
        for(Map.Entry<String,Integer> entry:set.entrySet()){
            if(minHeap.size()<k){
                minHeap.offer(entry);
            }else{
                Map.Entry<String,Integer> top=minHeap.peek();
                if(entry.getValue().compareTo(top.getValue())>0){
                    minHeap.poll();
                    minHeap.offer(entry);
                }else if (entry.getValue().compareTo(top.getValue())==0){
                    if(entry.getKey().compareTo(top.getKey())<0){
                        minHeap.poll();
                        minHeap.offer(entry);
                    }
                }
            }
        }
        List<String> list=new ArrayList<>();
        for(int i=0;i<k;i++){
            Map.Entry<String,Integer> temp=minHeap.poll();
            list.add(temp.getKey());
        }
        Collections.reverse(list);
        return list;
    }
}
